package com.syncshot.androidapp.activities;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.syncshot.androidapp.Constant;
import com.syncshot.androidapp.R;
import com.syncshot.androidapp.helper.ImageDownloader;
import com.syncshot.androidapp.helper.ImageDownloader.Mode;
import com.syncshot.androidapp.helper.WSHelper.Call;
import com.syncshot.androidapp.helper.WSHelper.WebserviceCaller;
import com.syncshot.androidapp.helper.WSHelper.WebserviceCaller.WebserviceCallerListener;
import com.syncshot.androidapp.model.Picture;
import com.syncshot.androidapp.util.WSUtil;

public class PictureListResultActivity extends AbstractActivity implements WebserviceCallerListener {

    private GridView          mGridView;
    private List<Picture>     mListPicture;
    private BroadcastReceiver mPictureTakenBroadcastReceiver;

    private ImageAdapter      mAdapter;
    private String            mEventId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_list_result);

        mListPicture = new ArrayList<Picture>();
        mEventId = getIntent().getStringExtra(Constant.KEY_EVENT_ID);

        mGridView = (GridView) findViewById(R.id.gridview);
        mAdapter = new ImageAdapter(this, mListPicture);
        mGridView.setAdapter(mAdapter);

        mGridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Object o = parent.getItemAtPosition(position);
                if (o instanceof Picture) {
                    Intent intent = new Intent(v.getContext(), PictureResultActivity.class);
                    intent.putExtra(PictureResultActivity.KEY_IMAGE_ID, ((Picture) o).getId());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        callWSListPicture();
        mPictureTakenBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.v("", "Refresh picture List");
                callWSListPicture();
            }
        };
        registerReceiver(mPictureTakenBroadcastReceiver, new IntentFilter(Constant.BROADCAST_PICTURE_TAKEN));
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPictureTakenBroadcastReceiver != null) {
            unregisterReceiver(mPictureTakenBroadcastReceiver);
        }
    }

    private void callWSListPicture() {
        WebserviceCaller ws = new WebserviceCaller(PictureListResultActivity.this);
        ws.execute(WSUtil.generateCallPictureList(mEventId));
    }

    @Override
    public void onResult(Call call, Object result) {
        if (result != null && result instanceof Picture[]) {
            Picture[] listPicture = (Picture[]) result;

            boolean changed = false;
            synchronized (mListPicture) {
                for (Picture pictSent : listPicture) {
                    if (!mListPicture.contains(pictSent)) {
                        mListPicture.add(pictSent);
                        changed = true;
                    }
                }
            }

            if (changed) {
                mAdapter.notifyDataSetChanged();
            }
        }

    }

    public class ImageAdapter extends ArrayAdapter<Picture> {

        public ImageAdapter(Context c, List<Picture> listPicture) {
            super(c, 0, 0, listPicture);
        }

        public long getItemId(int position) {
            return position;
        }

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) { // if it's not recycled, initialize some attributes
                imageView = new ImageView(getContext());
                imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
                ImageDownloader downloader = new ImageDownloader(null);
                downloader.setMode(Mode.CORRECT);
                imageView.setTag(downloader);
            } else {
                imageView = (ImageView) convertView;
            }

            ImageDownloader downloader = (ImageDownloader) imageView.getTag();
            Picture picture = getItem(position);
            downloader.download(WSUtil.generateUrlgetPicture(picture.getId(), true), imageView);
            return imageView;
        }
    }
}
